//
//  AppDelegate.m
//  DrugPin
//
//  Created by guohe on 2018/9/6.
//  Copyright © 2018年 outang. All rights reserved.
//
#import "KLoginViewController.h"
#import "AppDelegate.h"
#import "AppDelegate+AppService.h"

// 引入 JPush 功能所需头文件
#import "JPUSHService.h"
// iOS10 注册 APNs 所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
// 如果需要使用 idfa 功能所需要引入的头文件（可选）
#import <AdSupport/AdSupport.h>
@interface AppDelegate ()<JPUSHRegisterDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch
    
    // 初始化服务
    [self initService];
    
    // 初始化窗口
    [self initWindow];
    
    //向微信注册
    [WXApi registerApp:kAppKey_Wechat];
    
    //极光推送初始化 APNs 代码
    [self initJPushAPNsServersWithOptions:launchOptions];
    //极光推送初始化 JPush 代码
    [self initJPushServersWith:launchOptions];
    //获取 iOS 的推送内容通知
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
    // 本地通知内容获取：
    NSDictionary *localNotification = [launchOptions objectForKey: UIApplicationLaunchOptionsLocalNotificationKey];
    
    
    //  强推请求
    [self requestAPNS_Token];
    
    
    // 监测网络监听
    [self monitorNetworkStatus];
    return YES;
}

///  强推请求
- (void)requestAPNS_Token
{
    
    //2.1.9版本新增获取registration id block接口。
    // completionHandler 用于处理设置返回结果
    //  resCode 返回的结果状态码
    //  registrationID 返回 registrationID
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString* registrationID) {

        if (resCode == 0) {
            NSLog(@"registrationID获取成功：%@", registrationID);
            
//            [[SEGSystemAccountManager sharedSEGSystemAccountManager] requestSubmitToken:registrationID Finished:^(BOOL isSuccessed, NSString* codeType, NSString* errorMessage) {
//                NSLog(@"codeType = %@", codeType);
//            }];
        }
        else {
            NSLog(@"registrationID获取失败，code：%d", resCode);
        }
    }];
}

#pragma mark -  极光推送添加初始化 APNs 代码
-(void)initJPushAPNsServersWithOptions:(NSDictionary *)launchOptions{
    //notice: 3.0.0 及以后版本注册可以这样写，也可以继续用之前的注册方式
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义 categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    // apn 内容获取：
    NSDictionary *remoteNotification = [launchOptions objectForKey: UIApplicationLaunchOptionsRemoteNotificationKey];
    NSLog(@"###remoteNotification : %@",remoteNotification);

    if (remoteNotification) {//推送进入APP
        
        NSLog(@"app未启动，推送进入，直接显示预警界面");
        
//        [self SetMainTabbarController2]; //相应界面跳转方法
        
    }else{//正常进入APP
        
    }
    

}

#pragma mark - 极光推送添加初始化 JPush 代码
-(void)initJPushServersWith:(NSDictionary *)launchOptions{
    // Optional
    // 获取 IDFA 广告标识符（IDFA）
    // 如需使用 IDFA 功能请添加此代码并在初始化方法的 advertisingIdentifier 参数中填写对应值
    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    NSLog(@"#advertisingId = %@",advertisingId);

    
    // Required
    // init Push
    // notice: 2.1.5 版本的 SDK 新增的注册方法，改成可上报 IDFA，如果没有使用 IDFA 直接传 nil
    // 如需继续使用 pushConfig.plist 文件声明 appKey 等配置内容，请依旧使用 [JPUSHService setupWithOption:launchOptions] 方式初始化。
    [JPUSHService setupWithOption:launchOptions //launchingOption 启动参数.
                           appKey:kAppKey_JPush //appKey 一个JPush 应用必须的,唯一的标识. 请参考 JPush 相关说明文档来获取这个标识.
                          channel:kJPUSHChannel //发布渠道. 可选.
                 apsForProduction:@"1"]; //isProduction 是否生产环境. 如果为开发状态,设置为 NO; 如果为生产状态,应改为 YES.
                                                            //App 证书环境取决于profile provision的配置，此处建议与证书环境保持一致.
    [JPUSHService crashLogON];//开启Crash日志收集
    NSLog(@"kJPUSHAppKey = %@",kAppKey_JPush);
}

#pragma mark - networkDidReceiveMessage
- (void)networkDidReceiveMessage:(NSNotification *)notification {
    //    content：获取推送的内容
    //    messageID：获取推送的 messageID（key 为 @"_j_msgid"）
    //    extras：获取用户自定义参数
    //    customizeField1：根据自定义 key 获取自定义的 value
    NSDictionary * userInfo = [notification userInfo];
    NSString *content = [userInfo valueForKey:@"content"]; // content：获取推送的内容
    NSString *messageID = [userInfo valueForKey:@"_j_msgid"]; // messageID：获取推送的 messageID（key 为 @"_j_msgid"）
    NSDictionary *extras = [userInfo valueForKey:@"extras"]; // extras：获取用户自定义参数（服务端传递的 Extras 附加字段，key 是自己定义的）
    NSString *customizeField1 = [extras valueForKey:@"customizeField1"];// customizeField1：根据自定义 key 获取自定义的 value
}

//支持IOS9.0及以上
- (BOOL)application:(UIApplication*)app openURL:(NSURL*)url options:(NSDictionary*)options
{
    return [WXApi handleOpenURL:url delegate:self];
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

#pragma mark - 注册 APNs 成功并上报 DeviceToken
- (void)application:(UIApplication *)applicationdidRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}

#pragma mark - 实现注册 APNs 失败接口（可选）
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

#pragma mark- JPUSHRegisterDelegate 添加处理 APNs 通知回调方法
// iOS 10 Support 前台收到推送
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required:APNs 内容为 userInfo
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    //前台收到推送也可以弹出通知栏
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有 Badge、Sound、Alert 三种类型可以选择设置
}

// iOS 10 Support 点击通知栏调用
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
}

// NS_DEPRECATED_IOS(3_0, 10_0, "Use UserNotifications Framework's
//-[UNUserNotificationCenterDelegate willPresentNotification:withCompletionHandler:] or
//-[UNUserNotificationCenterDelegate didReceiveNotificationResponse:withCompletionHandler:] for user visible notifications and
//-[UIApplicationDelegate application:didReceiveRemoteNotification:fetchCompletionHandler:] for silent remote notifications")
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    NSDictionary *aps = [userInfo valueForKey:@"aps"]; // 取得 APNs 标准信息内容
    NSString *content = [aps valueForKey:@"alert"]; //推送显示的内容
    NSInteger badge = [[aps valueForKey:@"badge"] integerValue]; //badge 数量
    NSString *sound = [aps valueForKey:@"sound"]; //播放的声音
    
    // 取得 Extras 字段内容
    NSString *customizeField1 = [userInfo valueForKey:@"customizeExtras"]; //服务端中 Extras 字段，key 是自己定义的
    NSLog(@"content =[%@], badge=[%zd], sound=[%@], customize field  =[%@]",content,badge,sound,customizeField1);
    
    // iOS 10 以下 Required
    [JPUSHService handleRemoteNotification:userInfo];
}

//iOS 7 Remote Notification
- (void)application:(UIApplication *)application didReceiveRemoteNotification:  (NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    NSLog(@"this is iOS7 Remote Notification");
    
    // iOS 10 以下 Required
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}


#pragma mark - WXApiDelegate协议的方法
//授权后回调 WXApiDelegate ---- 程序实现和微信终端交互的具体请求与回应
-(void) onResp:(BaseResp*)resp{
    /*
     enum  WXErrCode {
     WXSuccess           = 0,    成功
     WXErrCodeCommon     = -1,  普通错误类型
     WXErrCodeUserCancel = -2,    用户点击取消并返回
     WXErrCodeSentFail   = -3,   发送失败
     WXErrCodeAuthDeny   = -4,    授权失败
     WXErrCodeUnsupport  = -5,   微信不支持
     };
     
     回调参数说明：
     code    用户换取access_token的code，仅在ErrCode为0时有效
     state   第三方程序发送时用来标识其请求的唯一性的标志，由第三方程序调用sendReq时传入，由微信终端回传，state字符串长度不能超过1K
     lang    微信客户端当前语言
     country 微信用户当前国家信息
     */
    if ([resp isKindOfClass:[SendAuthResp class]]) {   //授权登录的类。
        if (resp.errCode == 0) {  //成功。
            SendAuthResp *resp2 = (SendAuthResp *)resp;
            //[[NSNotificationCenter defaultCenter] postNotificationName:@"wxLogin" object:resp2.code];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"wechatDidLoginNotification" object:self userInfo:@{@"code":resp2.code}];
        }else{ //失败
            ErrorShow(@"授权失败")
        }
    }
}



@end
